﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;

namespace template_dll
{
    public partial class Form2 : Form
    {
        private SqlConnection conn;
        private DataTable dt_rep;
        public string sortcoumn;
        public string namechcol = "Флаг";

        public Form2()
        {
            InitializeComponent();
        }

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            //- Загрузка данных
            this.Text = "Аптеки";
            sortcoumn = "Аптека";
            conn = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True");
            SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[1];
            par[0].name = "@flag_print";
            par[0].value = 0;
            dt_rep = (new SqlStorProc()).SqlProcExecWithQueryOneTable(conn, "pas_PrintPharmDrugs", 60, par);
            dataGridView1.DataSource = dt_rep.DefaultView;
            if (dataGridView1.DataSource != null)
            {
                dataGridView1.Sort(dataGridView1.Columns[sortcoumn], ListSortDirection.Ascending);
                HideShowRows();
            }


        }

        private void button1_Click(object sender, EventArgs e)
        {
            //- Сохранить и выйти
            savePharm();
            this.Close();
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //- Закрыть форму без сохранения
            this.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //- Отметить все аптеки
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                dataGridView1.Rows[i].Cells[0].Value = 1;
            }
            dataGridView1.Refresh();
            savePharm();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //- Снять отметки
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                dataGridView1.Rows[i].Cells[0].Value = 0;
            }
            dataGridView1.Refresh();
            savePharm();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //- Поиск аптеки
            HideShowRows();

        }

        private void savePharm()
        {
            //- Сохранить изменения
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[9];
                par[0].name = "@flag_ins";
                par[0].value = 0;
                par[1].name = "@pharmcode";
                par[1].value = Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
                par[2].name = "@flag_bit";
                par[2].value = Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value);
                par[3].name = "@drugcode";
                par[3].value = null;
                par[4].name = "@delta";
                par[4].value = null;
                par[5].name = "@sign";
                par[5].value = null;
                par[6].name = "@flag_new";
                par[6].value = null;
                par[7].name = "@date_b";
                par[7].value = null;
                par[8].name = "@date_e";
                par[8].value = null;

                int rez = 0;
                rez = (new SqlStorProc()).SqlProcExecNonQuery(conn, "[pas_InsPharmDrugs]", 30, par);

                conn.Close();
            }
        }

        private void HideShowRows()
        {
            CurrencyManager cm = (CurrencyManager)dataGridView1.BindingContext[dataGridView1.DataSource];
            cm.SuspendBinding();
            int select = 0;
            int filter = 0;
            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                r.Visible = true;
                r.DefaultCellStyle.BackColor = SystemColors.ControlLightLight;

                if (!Regex.Match(Convert.ToString(dataGridView1[dataGridView1.SortedColumn.Name, r.Index].Value), textBox1.Text, RegexOptions.IgnoreCase).Success)
                    r.Visible = false;

                if (checkBox1.Checked)
                    if (!Convert.ToBoolean(dataGridView1[namechcol, r.Index].Value)) r.Visible = false;

                if (Convert.ToBoolean(dataGridView1[namechcol, r.Index].Value))
                {
                    select++;
                    r.DefaultCellStyle.BackColor = Color.Red;
                }
                if (r.Visible) filter++;
            }
            cm.ResumeBinding();
            ToolStripItemsUpd(dataGridView1.Rows.Count, select, filter);
            savePharm();
        }

        private void ToolStripItemsUpd(int all, int select, int filter)
        {
            statusStrip1.Items.Clear();
            statusStrip1.Items.Add("Всего строк " + all.ToString());
            statusStrip1.Items.Add("Отфильтровано " + filter.ToString());
            statusStrip1.Items.Add("Выбранно " + select.ToString());
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //- Отметить видимые
            CurrencyManager cm = (CurrencyManager)dataGridView1.BindingContext[dataGridView1.DataSource];
            cm.SuspendBinding();
            int select = 0;
            int filter = 0;
            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                if (r.Visible)
                {
                    dataGridView1[namechcol, r.Index].Value = true;
                    r.DefaultCellStyle.BackColor = Color.Red;
                    select++;
                    filter++;
                }
                else
                {
                    if (Convert.ToBoolean(dataGridView1[namechcol, r.Index].Value)) select++;
                }
            }
            cm.ResumeBinding();
            ToolStripItemsUpd(dataGridView1.Rows.Count, select, filter);
            savePharm();

        }

        private void button6_Click(object sender, EventArgs e)
        {
            //- Снять отметки с видимых
            CurrencyManager cm = (CurrencyManager)dataGridView1.BindingContext[dataGridView1.DataSource];
            cm.SuspendBinding();
            int select = 0;
            int filter = 0;
            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                if (r.Visible)
                {
                    dataGridView1[namechcol, r.Index].Value = false;
                    r.DefaultCellStyle.BackColor = SystemColors.ControlLightLight;
                    filter++;
                }
                if (Convert.ToBoolean(dataGridView1[namechcol, r.Index].Value))
                {
                    select++;
                }
            }
            cm.ResumeBinding();
            ToolStripItemsUpd(dataGridView1.Rows.Count, select, filter);
            savePharm();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            //- Показать\скрыть отмеченные
            HideShowRows();
        }
    }
}
